#!/usr/bin/env python3
"""
Windows主机监控模块 - 通过网络API或共享卷监控Windows物理机资源
"""

import os
import json
import time
import psutil
import platform
from typing import Dict, Optional
import logging

logger = logging.getLogger(__name__)

class WindowsHostMonitor:
    """Windows主机监控器 - 适用于Windows Docker环境"""
    
    def __init__(self, shared_data_path: str = "/app/data/host_stats.json"):
        """
        初始化Windows主机监控器
        
        Args:
            shared_data_path: 共享数据文件路径
        """
        self.shared_data_path = shared_data_path
        self.is_windows_host = self._detect_windows_host()
        self.fallback_monitor = psutil
        
        if self.is_windows_host:
            logger.info("检测到Windows主机环境，将尝试读取共享数据文件")
        else:
            logger.info("未检测到Windows主机环境，使用本地监控")
    
    def _detect_windows_host(self) -> bool:
        """检测是否为Windows主机环境"""
        # 检查是否存在共享数据文件
        if os.path.exists(self.shared_data_path):
            return True
        
        # 检查环境变量
        if os.environ.get('WINDOWS_HOST_MONITORING', '').lower() == 'true':
            return True
            
        return False
    
    def _read_host_stats(self) -> Optional[Dict]:
        """读取主机统计数据"""
        try:
            if os.path.exists(self.shared_data_path):
                with open(self.shared_data_path, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    # 检查数据是否过期（超过5分钟）
                    if time.time() - data.get('timestamp', 0) < 300:
                        return data
                    else:
                        logger.warning("主机数据已过期，使用本地数据")
        except Exception as e:
            logger.error(f"读取主机数据失败: {e}")
        return None
    
    def get_cpu_info(self) -> Dict:
        """获取CPU信息"""
        host_data = self._read_host_stats()
        if host_data and 'cpu' in host_data:
            return host_data['cpu']
        
        # 回退到本地监控
        return {
            'percent': psutil.cpu_percent(interval=1),
            'count': psutil.cpu_count(),
            'frequency': psutil.cpu_freq().current if psutil.cpu_freq() else 0,
            'load_avg': [0, 0, 0],  # Windows不支持load average
            'source': 'container_local'
        }
    
    def get_memory_info(self) -> Dict:
        """获取内存信息"""
        host_data = self._read_host_stats()
        if host_data and 'memory' in host_data:
            return host_data['memory']
        
        # 回退到本地监控
        memory = psutil.virtual_memory()
        return {
            'total': memory.total,
            'available': memory.available,
            'used': memory.used,
            'percent': memory.percent,
            'source': 'container_local'
        }
    
    def get_disk_info(self) -> Dict:
        """获取磁盘信息"""
        host_data = self._read_host_stats()
        if host_data and 'disk' in host_data:
            return host_data['disk']
        
        # 回退到本地监控
        disk_info = {}
        try:
            for partition in psutil.disk_partitions():
                try:
                    usage = psutil.disk_usage(partition.mountpoint)
                    disk_info[partition.mountpoint] = {
                        'total': usage.total,
                        'used': usage.used,
                        'free': usage.free,
                        'percent': (usage.used / usage.total) * 100
                    }
                except:
                    continue
        except Exception as e:
            logger.error(f"获取磁盘信息失败: {e}")
        
        return disk_info
    
    def get_network_info(self) -> Dict:
        """获取网络信息"""
        host_data = self._read_host_stats()
        if host_data and 'network' in host_data:
            return host_data['network']
        
        # 回退到本地监控
        try:
            net_io = psutil.net_io_counters()
            return {
                'bytes_sent': net_io.bytes_sent,
                'bytes_recv': net_io.bytes_recv,
                'packets_sent': net_io.packets_sent,
                'packets_recv': net_io.packets_recv,
                'source': 'container_local'
            }
        except Exception as e:
            logger.error(f"获取网络信息失败: {e}")
            return {}
    
    def get_comprehensive_status(self) -> Dict:
        """获取综合系统状态"""
        host_data = self._read_host_stats()
        
        return {
            'cpu': self.get_cpu_info(),
            'memory': self.get_memory_info(),
            'disk': self.get_disk_info(),
            'network': self.get_network_info(),
            'monitoring_info': {
                'is_windows_host': self.is_windows_host,
                'has_host_data': host_data is not None,
                'data_source': 'windows_host' if host_data else 'container_local',
                'last_update': host_data.get('timestamp') if host_data else time.time()
            }
        }